<template>
  <div class="app">
    <Panel>
      <van-nav-bar
        slot="header"
        :title="headerTitle"
        :left-text="leftText"
        :right-text="rightOptions.label"
        :left-arrow="!this.routerPath.includes($route.path)"
        :fixed="false"
        @click-left="leftEvent"
      >
        <!--  插槽，自定义右侧按钮  -->
        <template v-if="rightOptions.label" #right>
          <div @click="rightOptions.handle">
            <van-icon
              v-if="rightOptions.icon"
              :name="rightOptions.icon"
              :size="rightOptions.iconSize"
            />
            <span>{{rightOptions.label}}</span>
          </div>
        </template>
      </van-nav-bar>
      <router-view
        :setHeaderLeft="setHeaderLeft"
        :setLeftText="setLeftText"
        :setHeaderRight="setHeaderRight"
        :setHeaderTitle="setHeaderTitle"
      />
      <van-tabbar
        slot="footer"
        v-if="tabbarDisplay"
        v-model="active"
        :fixed="false"
        active-color="#ee0a24"
        inactive-color="#000"
      >
        <van-tabbar-item to="/" icon="home-o">Home</van-tabbar-item>
        <van-tabbar-item to="/task" icon="search">任务</van-tabbar-item>
        <van-tabbar-item to="/info" icon="friends-o">信息</van-tabbar-item>
        <van-tabbar-item to="/personal" icon="setting-o">个人中心</van-tabbar-item>
      </van-tabbar>
    </Panel>
  </div>
</template>
<script>
import Panel from '@/components/Panel'
import { isEmptyObject } from '@/utils'
export default {
  name: 'App',
  components: {
    Panel
  },
  data () {
    return {
      active: 0,
      headerTitle: this.$route.name,
      leftText: '',
      leftEvent: this.clickLeft,
      routerPath: ['/', '/task', '/info', '/personal'],
      rightOptions: {} // 图标name，大小，位置
    }
  },
  computed: {
    tabbarDisplay () { // tabbar显示状态
      return this.routerPath.includes(this.$route.path)
    }
  },
  watch: {
    '$route.name': function (n) {
      this.headerTitle = n
    }
  },
  beforeUpdate () {
    if (!isEmptyObject(this.rightOptions) && this.rightOptions.path !== this.$route.path) { // 更新右侧配置
      this.rightOptions = {}
    }
  },
  methods: {
    // 设置header title
    setHeaderTitle (title = '') {
      if (!title) return
      this.headerTitle = title
    },
    // 设置左侧文字
    setLeftText (title = '') {
      if (!title) return
      this.leftText = title
    },
    // 设置头部左侧点击事件
    setHeaderLeft (event = () => { }) {
      this.leftEvent = event
    },
    // header右侧按钮配置，handle实践，label显示文本,icon
    setHeaderRight (options = { handle: () => { }, label: '', icon: '', iconSize: '' }) {
      this.rightOptions = options
    },
    clickLeft () {
      this.$router.back()
    }
  }
}
</script>
